/**
 *
 */
package com.cbwl.eoas.cms.web.controller.login;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cbwl.eoas.cms.api.sysconfig.ISysResourceService;
import com.cbwl.eoas.cms.api.sysconfig.ISysUserService;
import com.cbwl.eoas.cms.model.sysconfig.SysResourceDTO;
import com.cbwl.eoas.cms.model.sysconfig.SysUserDTO;
import com.cbwl.eoas.common.framework.session.SecurityUserDTO;
import com.cbwl.eoas.common.framework.session.SessionManager;
import com.cbwl.eoas.common.util.Md5Util;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


/**
 * 登陆请求
 *
 * @author yyb
 *
 */
@Controller
@RequestMapping("main")
@Api(value="用户登录controller")
public class LoginController
{
	/**
	 * 日志句柄
	 */
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);

	
	//业务层注解
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
	private ISysResourceService sysResourceService;
	
	@RequestMapping(value="/login",method = RequestMethod.GET)
	@ApiOperation(value="登录界面",notes="跳转到首页")
	public String tologin(HttpServletRequest request,@ApiParam(name="用户类型",value="json格式",required=true)String userType)
	{
		return "loginInit";
	}
	
	@RequestMapping("/loginout")
	public String loginout(HttpServletRequest request) {
		request.getSession().removeAttribute("securityUser");
		return "loginInit";
	}
	

	@RequestMapping(value="/loginsuccess" ,method = RequestMethod.GET)
	public String toLoginsuccess(HttpServletRequest request,String userType)
	{
		request.setAttribute("menuList", queryMenus(new SysResourceDTO()));
		return "MainPageDef";
	}
	
	
	@RequestMapping(value="/loginCheck" ,method = RequestMethod.POST)
	@ResponseBody
	public String loginCheck(HttpServletRequest request,String userLoginname,String userPassword)
	{
		Subject user = SecurityUtils.getSubject();
		String error = "";
		if (user.getSession(true).getAttribute("securityUser") == null) {
			if (StringUtils.isEmpty(userLoginname) || StringUtils.isEmpty(userPassword)) {
				error = "用户名或者密码不能为空！";
				return error;
			}
		}
		UsernamePasswordToken token = null;
		try {
			// 通过登录名获取用户信息
			SysUserDTO sysuser = new SysUserDTO();
			sysuser.setUserLoginname(userLoginname);
			SysUserDTO sysUser = sysUserService.getUserDTOByParam(sysuser);
			if (sysUser == null) {
				throw new IncorrectCredentialsException("账号信息有误，请确认后重试！");
			}
			if (sysUser.getUserStatus().equals("101")) {
				// 登录密码
				token = new UsernamePasswordToken(userLoginname, Md5Util.encodePassword(userPassword, sysUser.getUserJobno()));
				token.setRememberMe(true);
				user.login(token);
			} else if (sysUser.getUserStatus().equals("102")) {
				throw new AuthenticationException();
			} else {
				// 禁止登陆 状态错误·
				throw new UnknownAccountException();
			}
			// 登录成功后，通过用户名获取用户所有的权限
			 SecurityUserDTO suser = sysUserService.getSecurityUserByLoginName(sysUser);
			if (suser == null) {
				throw new IncorrectCredentialsException();
			}
			logger.debug("LoginController:" + user.getSession(true).getId());
			return "success";
		} catch (UnknownAccountException e) {
			error = "用户名或密码错误!";
		} catch (IncorrectCredentialsException e) {
			error = "用户名或密码错误!";
		} catch (AuthenticationException e) {
			if (token != null) {
				token.clear();
			}
			// 其他错误，比如锁定，如果想单独处理请单独catch 处理
			error = "账号信息有误，请确认后重试!";
		}
		return error;
	}
	
	
	List<SysResourceDTO> queryMenus(SysResourceDTO bean){
		bean.setUid(SessionManager.getCurrentUser().getId());
		return sysResourceService.queryMenupatterns(bean);
	}
	

	
}
